const APPID = require("../../utils/config.js").APPID;
const AgoraMiniappSDK = require("../../lib/Agora_Miniapp_SDK_for_WeChat.js");
import fetch from '../../utils/services'

const {
  windowWidth,
  windowHeight
} = wx.getSystemInfoSync()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    type: {
      type: String,
      value: '1'
    },
    isScaled: {
      type: Boolean,
      value: false
    },
    userInfo: {
      type: Object,
      value: {}
    },
    myInfo: {
      type: Object,
      value: {}
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    pusherContext: null,
    enableCamera: true, //是否调用摄像头
    enableCameraPlayer: true, // 远端视频是否调用摄像头
    toggle: false, // 是否切换了视窗
    muted: false, //是否静音
    hasFree: false, //是否免提
    time: 0,
    timeStr: '00:00',
    waitConect: true,
    showCircleIcon: false, //录制icon展示与否， 闪烁效果
    transcribe: false, //是否在录制
    transcribeTime: 0,
    transcribeTimeStr: '00:00',
    puserPosition: {
      x: 800,
      y: windowHeight - 300
    },
    playerPosition: {
      x: 0,
      y: 0
    },
    currentPosition: {
      x: 800,
      y: windowHeight - 300
    },
    showPusher: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 初始化Agora
    initAgoraChannel: function(tooken, uid, channel) {
      console.log('加入频道',tooken,uid,channel)
      return new Promise((resolve, reject) => {
        const client = new AgoraMiniappSDK.Client()
        this.subscribeEvents(client);
        this.client = client;
        this.client.setRole('broadcaster');
        this.client.init(APPID, () => {
          this.client.join(tooken, channel, uid, () => {
              this.client.publish(url => {
                console.log('发布成功')
                resolve(url);
              }, e => {
                reject(e)
              });
          }, e => {
            reject(e)
          })
        }, e => {
          reject(e);
        });
      });
    },
    // 绑定Agora 监听事件
    subscribeEvents: function(client) {
      // 通知应用程序已添加远端音视频流。
      client.on("stream-added", e => {
        console.log('加入成功')
        let uid = e.uid;
        client.subscribe(uid, (url, rotation) => {
          const { userInfo } = this.data
          userInfo.url = url
          userInfo.uid = uid
          this.setData({ userInfo })
          setTimeout(() => {
            this.setData({ showPusher: false })
          }, 2000)
          setTimeout(() => {
            this.setData({ showPusher: true })
          }, 2500)
        }, e => {
          console.log(1, e)
        });
      });
       // 通知应用程序远端视频已旋转
      client.on("video-rotation", (e) => {
        setTimeout(() => {
          const player = this.getPlayerComponent(e.uid);
          player && player.rotate(e.rotation);
        }, 200);
      });
      // 通知应用程序已删除远端音视频流。
      client.on('stream-removed', e => {       
        this.streamRemoved()
      });
      // 通知应用程序已更新 Url 地址。
      client.on('update-url', e => {
        console.log(1234567, e.url)
      });
    },
    // 获取推流元素
    getPusherComponent: function() {
      const agorapusher = this.selectComponent('#my_pusher');
      return agorapusher;
    },
    // 获取远端流元素
    getPlayerComponent: function(uid) {
      const agoraPlayer = this.selectComponent('#my_player');
      return agoraPlayer;
    },
    // 缩放视窗
    scaleActionImg: function() {
      if (this.data.isScaled) {
        this.triggerEvent('scaleAction', {}, {})
      } else {
        this.toggleWicket()
      }
    },
    // 缩放视窗
    scaleAction: function() {
      this.triggerEvent('scaleAction', {}, {})
    },
    // 转换摄像头
    reversalAction: function() {
      const agoraPusher = this.getPusherComponent();
      agoraPusher && agoraPusher.switchCamera();
    },
    // 音量控制
    volumeAction: function() {
      if (!this.data.muted) {
        this.client.muteLocal(
          'audio',
          function() {
          },
          function() {
            console.log('错误11')
          }
        )
      } else {
        this.client.unmuteLocal(
          'audio',
          function() {
          },
          function() {
            console.log('错误22')
          }
        )
      }
      this.setData({ muted: !this.data.muted })
    },
    // 免提控制
    handsFreeAction: function() {
      this.setData({ hasFree: !this.data.hasFree })
    },
    // 挂断
    declineAction: function() {
      wx.showLoading({
        title: '正在挂断视频',
      })
      this.client.unpublish(() => {
        this.client.leave(() => {
          this.client.destroy(() => {
            wx.hideLoading()
            this.triggerEvent('destroy', {}, {})
          })
        })
      })
    },
    // 对面挂断了
    streamRemoved: function() {
      this.client.unpublish(() => {
        this.client.leave(() => {
          this.client.destroy(() => {
            wx.hideLoading()
            this.triggerEvent('streamRemoved', {}, {})
          })
        })
      })
    },
    // 摄像头控制
    cameraAction: function() {
      const that = this
      if (this.data.enableCamera) {
        this.client.muteLocal(
          'video',
          function() {
            that.setData({ enableCamera: !that.data.enableCamera })
          },
          function() {
            console.log('错误11')
          }
        )
      } else {
        this.client.unmuteLocal(
          'video',
          function() {
            console.log('22')
            that.setData({ enableCamera: !that.data.enableCamera })
          },
          function() {
            console.log('错误11')
          }
        )
      }
    },
    // 移动位置， 保存位置
    changePosition: function(e) {
      console.log(e)
      if (e.detail) {
       const currentPosition = {
          x: e.detail.x,
          y: e.detail.y,
       }
       this.setData({ currentPosition })
      } else {
        const currentPosition = {
          x: e.x,
          y: e.y,
        }
        this.setData({ currentPosition })
      }
    },
    // 视窗交换
    toggleWicket: function(e) {
      if (!this.data.toggle && e.currentTarget.id !== 'my_pusher') {
        return
      }
      if (this.data.toggle && e.currentTarget.id === 'my_pusher') {
        return
      }
      let puserPosition = {
        x: !this.data.toggle ? 0 : this.data.currentPosition.x,
        y: !this.data.toggle ? 0 : this.data.currentPosition.y
      }
      let playerPosition = {
        x: this.data.toggle ? 0 : this.data.currentPosition.x,
        y: this.data.toggle ? 0 : this.data.currentPosition.y
      }
      this.setData({
        toggle: !this.data.toggle,
        puserPosition,
        playerPosition
      }, () => {
        this.changePosition(!this.data.toggle ? puserPosition : playerPosition)
      })
    },
    // 正在录制音视频
    getTranscribe: function(converseCode) {
      if (this.data.transcribe) { // 已经在录制中了
        return
      }
      fetch.post('/converse/timeCloudRecord', { converseCode }).then(data => {
        const transcribeTime = parseInt(data / 1000, 10)
        this.setData({ transcribeTime, transcribe: true }, () => {
          // this.startSetInter2() // 定时器
        })
      })
    },
    init: function() {
      wx.setKeepScreenOn({
        keepScreenOn: true
      });
      this.setData({ hasFree: this.data.type === '1' ? true : false })
      const channel = this.data.userInfo.converseCode || '1000';
      const uid = this.data.myInfo.uid || Math.random() * 100;
      const tooken = this.data.userInfo.resourceToken || undefined
      const that = this
      this.initAgoraChannel(tooken, uid, channel).then(url => {
        const myInfo = this.data.myInfo
        myInfo.url = url
        myInfo.uid = uid
        that.setData({ myInfo, waitConect: false })
        that.startSetInter()
      }).catch(e => {
        console.log(e)
        wx.showToast({
          title: `客户端初始化失败`,
          icon: 'none',
          duration: 2000
        });
      });
    },
    getTimeStr: function(time) {
      let munites = parseInt(time / 60, 10)
      let seconds = time % 60
      if (munites < 10) {
        munites = '0' + munites
      }
      if (seconds < 10) {
        seconds = '0' + seconds
      }
      this.setData({ timeStr: `${munites}:${seconds}`})
    },
    startSetInter: function(){
      var that = this;
      that.data.setInter = setInterval(
        function () {
           const time = that.data.time + 1;
           that.setData({ time });
           that.getTimeStr(time)
        }, 1000);
    },
    getTimeStr2: function(time) {
      let munites = parseInt(time / 60, 10)
      let seconds = time % 60
      if (munites < 10) {
        munites = '0' + munites
      }
      if (seconds < 10) {
        seconds = '0' + seconds
      }
      this.setData({ transcribeTimeStr: `${munites}:${seconds}`})
    },
    startSetInter2: function(){
      var that = this;
      that.data.setInter = setInterval(
        function () {
          const transcribeTime = that.data.transcribeTime + 1;
          that.setData({ transcribeTime });
          that.getTimeStr2(transcribeTime)
        }, 1000);
    },
  },
  ready: function() {
    this.init()
  },

  detached: function() {
    clearInterval(this.data.setInter)
    this.client.leave(
      () => {
        console.log('退出成功')
        this.client.destroy(
          () => {
            console.log('销毁成功')
            // wx.showToast({
            //   title: '销毁成功',
            //   icon: 'none',
            //   duration: 2000
            // })
          },
          () => {
            console.log('销毁失败')
          }
        )
      },
      () => {
        console.log('退出失败')
      }
    )
  }
})
